<template>
    <el-dialog
        v-model="isShow"
        :align-center="true"
        :close-on-click-modal="false"
        :destroy-on-close="true"
        :title="formType === 'add' ? '添加地区' : '编辑地区'"
        class="dialog-box"
        @close="onCloseDialog"
    >
        <el-scrollbar max-height="450px">
            <el-form label-width="100" ref="formRef" :model="regionForm" :rules="rules">
                <el-form-item label="上级地区">
                    <el-tree-select
                        ref="selectParentRef"
                        v-model="regionForm.parentId"
                        placeholder="请选择上级地区"
                        :data="regions"
                        node-key="id"
                        :props="regionsProps"
                        render-after-expand
                        clearable
                        filterable
                        @node-click="onSelectParent"
                        @clear="onClearSelect"
                    ></el-tree-select>
                </el-form-item>
                <el-form-item prop="type" label="类型">
                    <el-select v-model="regionForm.type" placeholder="请选择类型" clearable>
                        <el-option
                            v-for="(item, index) in regionType"
                            :key="index"
                            :value="item.value"
                            :label="item.label"
                            :disabled="item.disabled"
                        ></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item prop="name" label="地区名称">
                    <el-input v-model="regionForm.name" placeholder="请输入地区名称" clearable></el-input>
                </el-form-item>
                <el-form-item prop="code" label="地区编码">
                    <el-input v-model="regionForm.code" placeholder="请输入地区编码" clearable></el-input>
                </el-form-item>
            </el-form>
        </el-scrollbar>
        <template #footer>
            <el-button @click="onCancel">取消</el-button>
            <el-button @click="onConfirm" type="primary">确认</el-button>
        </template>
    </el-dialog>
</template>

<script setup lang="tsx">
import { AddressType, RegionForm } from '@/api/system/region/type'
import { FormInstance, FormRules } from 'element-plus'

const emit = defineEmits<{ onTableAction: [action: TableActionType, params: any] }>()
// 是否显示dialog
const isShow = ref(false)
// 表单实例 Ref
const formRef = ref<FormInstance>()
// 表单类型
const formType = ref<FormType>('add')
// 表单初始数据
const initform: Partial<RegionForm> = {
    id: undefined,
    name: '',
    code: '',
    type: undefined,
    parentId: undefined,
}
// 地区类型
const regionType = reactive<SelectOptions[]>([
    {
        label: '省份/直辖市/特别行政区',
        value: 1,
    },
    {
        label: '城市',
        value: 2,
    },
    {
        label: '县/区',
        value: 3,
    },
    {
        label: '镇/乡/街道',
        value: 4,
    },
    {
        label: '村/社区',
        value: 5,
    },
])
// 表单数据
const regionForm = reactive<Partial<RegionForm>>({ ...initform })
// 表单校验规则
const rules = reactive<FormRules<RegionForm>>({
    name: [
        {
            type: 'string',
            required: true,
            message: '地区名称不能为空',
            trigger: 'change',
        },
    ],
    type: [
        {
            type: 'number',
            required: true,
            message: '地区类型不能为空',
            trigger: 'change',
        },
    ],
    code: [
        {
            type: 'string',
            required: true,
            message: '地区编码不能为空',
            trigger: 'change',
        },
        {
            pattern: /^[A-Za-z0-9]+[A-Za-z0-9]*$/,
            message: '地区编码必须是字母或者数字',
            trigger: 'change',
        },
    ],
})
// 选择上级下拉框
const selectParentRef = ref()
const regions = ref<AddressType[]>()
const regionsProps = { label: 'name', value: 'id', children: 'children' }

watch(
    () => isShow.value,
    () => {
        if (isShow.value) {
            getTreeRegions()
        }
    },
)
// 获得上级地区树
const getTreeRegions = async () => {
    const result = await getRegions()
    if (result.isSuccess) {
        regions.value = result.data
    }
}
// 选择上级触发
const onSelectParent = (region: RegionForm) => {
    regionForm.parentId = region.id
    switch (region.type) {
        case 1:
            regionForm.type = 2
            regionType.forEach((item) => (item.disabled = (item.value as number) !== 2 ? true : false))
            break
        case 2:
            regionForm.type = 3
            regionType.forEach((item) => (item.disabled = (item.value as number) !== 3 ? true : false))
            break
        case 3:
            regionForm.type = 4
            regionType.forEach((item) => (item.disabled = (item.value as number) !== 4 ? true : false))
            break
        case 4:
            regionForm.type = 5
            regionType.forEach((item) => (item.disabled = (item.value as number) !== 5 ? true : false))
            break
        default:
            break
    }
    // 选择节点后，隐藏下拉框
    nextTick(() => {
        if (selectParentRef.value) {
            selectParentRef.value.blur()
        }
    })
}
// 清空上级选择
const onClearSelect = () => {
    regionForm.parentId = undefined
    regionForm.type = undefined
    regionType.forEach((item) => (item.disabled = false))
}
// 打开dialog
const onOpenDialog = (action: FormType, row?: RegionForm) => {
    formType.value = action
    if (action !== 'add' && row) {
        Object.assign(regionForm, row)
    } else if (action === 'add') {
        Object.assign(regionForm, initform)
    }
    isShow.value = true
}
// 关闭dialog
const onCloseDialog = () => {
    isShow.value = false
}
// 取消
const onCancel = () => onCloseDialog()
// 完成确认
const onConfirm = async () => {
    await formRef.value?.validate()

    emit('onTableAction', 'addOrEditSubmit', regionForm)
}
defineExpose({
    onOpenDialog,
    onCloseDialog,
})
</script>

<style lang="scss" scoped></style>
